<?php

use Workerman\Worker;
use Workerman\Timer;
use PHPSocketIO\SocketIO;
use Workerman\Protocols\Http\Request;
use Workerman\Connection\TcpConnection;
use think\Log;

include __DIR__ . '/vendor/autoload.php';

//导入插件配置信息
$config = include(__DIR__ . '/../../config.php');
$config = array_reduce($config, function ($pre, $item) {
    $pre[$item['name']] = trim($item['value']);
    return $pre;
}, []);


// print_r($config);

// exit();

// 开启websocket协议服务
$ws_worker = new Worker("websocket://0.0.0.0:" . $config['websocket_port']);

// 启动1个进程对外提供服务
$ws_worker->count = 1;

// 新增加一个属性，用来保存uid到connection的映射
$ws_worker->uidConnections = array();


// 当收到客户端发来的数据后返回hello $data给客户端
$ws_worker->onMessage = function(TcpConnection $connection, $data)
{
    global $ws_worker;
    // 判断当前客户端是否已经验证,既是否设置了uid
    if(!isset($ws_worker->uidConnections[$connection->id]))
    {
        echo "new connection: " . $connection->id . "\n";
        $ws_worker->uidConnections[$connection->id] = $connection;
    }

    // 解析数据
    $result = json_decode($data, true);

    switch ($result['event']) {
        case 'ping':
            $connection->send(json_encode(['event' => 'pong', 'data' => '']));
            break;
        default:
            $connection->send($data);
            break;
    }
};


// 监听WebSocket连接打开事件
$ws_worker->onWorkerStart = function($ws_worker) use ($config) {

    // 设置2345的web服务，用于接收http请求
    $inner_http_worker = new Worker('http://0.0.0.0:' . $config['websocket_push_port']);

    $inner_http_worker->onMessage = function (TcpConnection $http_connection, Request $request) {
        global $uidConnectionMap;
        $post = $request->post();
        $post = $post ? $post : $request->get();

        print_r($post);

        // 推送数据的url格式 type=publish&to=uid&content=xxxx
        switch (@$post['type']) {
            case 'publish':
                broadcast(['event' => 'publish', 'data' => $post]);
                $http_connection->send('ok');
                break;
            case 'fullon':
                broadcast(['event' => 'fullon', 'data' => $post]);
                $http_connection->send('ok');
                break;
            case 'fulloff':
                broadcast(['event' => 'fulloff', 'data' => $post]);
                $http_connection->send('ok');
                break;
            case 'singleon':
                broadcast(['event' => 'singleon', 'data' => $post]);
                $http_connection->send('ok');
                break;
            case 'singleoff':
                broadcast(['event' => 'singleoff', 'data' => $post]);
                $http_connection->send('ok');
                break;
            case 'address':
                broadcast(['event' => 'address', 'data' => $post]);
                $http_connection->send('ok');
                break;
            case 'status':
                broadcast(['event' => 'status', 'data' => $post]);
                $http_connection->send('ok');
                break;
            // default:
            //     $http_connection->send('fail');
            //     break;
        }
        return $http_connection->send('fail');
    };
    // 执行监听
    $inner_http_worker->listen();
};


// 当有客户端连接断开时
$ws_worker->onClose = function(TcpConnection $connection)
{
    global $ws_worker;
    if(isset($ws_worker->uidConnections[$connection->id]))
    {
        // 连接断开时删除映射
        unset($ws_worker->uidConnections[$connection->id]);
    }
};

// 向所有验证的用户推送数据
function broadcast($message)
{
   global $ws_worker;

   foreach($ws_worker->uidConnections as $connection)
   {
        print_r('广播: ' . $connection->id . "\n");
        $connection->send(json_encode($message));
   }
}

// 针对uid推送数据
function sendMessageByUid($uid, $message)
{
    global $ws_worker;
    if(isset($ws_worker->uidConnections[$uid]))
    {
        $connection = $ws_worker->uidConnections[$uid];
        $connection->send($message);
        return true;
    }
    return false;
}

if (!defined('GLOBAL_START')) {
    Worker::runAll();
}